package com.runvp.service.biz.service.impl;

import com.runvp.common.core.text.Convert;
import com.runvp.common.enums.BillChangeType;
import com.runvp.common.enums.EnableStatus;
import com.runvp.common.exception.base.BaseException;
import com.runvp.common.util.BigDecimalUtil;
import com.runvp.common.util.OrderNoUtils;
import com.runvp.common.util.auth.SecurityUtils;
import com.runvp.common.utils.DateUtils;
import com.runvp.service.biz.domain.BizCustomer;
import com.runvp.service.biz.domain.BizCustomerTranLog;
import com.runvp.service.biz.domain.BizCustomerWallet;
import com.runvp.service.biz.mapper.BizCustomerMapper;
import com.runvp.service.biz.mapper.BizCustomerTranLogMapper;
import com.runvp.service.biz.mapper.BizCustomerWalletMapper;
import com.runvp.service.biz.service.IBizCustomerWalletService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * 用户钱包Service业务层处理
 * 
 * @author runvp
 * @date 2022-11-05
 */
@Slf4j
@Service
public class BizCustomerWalletServiceImpl implements IBizCustomerWalletService {
    @Autowired
    private BizCustomerMapper bizCustomerMapper;
    @Autowired
    private BizCustomerWalletMapper bizCustomerWalletMapper;
    @Autowired
    private BizCustomerTranLogMapper bizCustomerTranLogMapper;
    /**
     * 查询用户钱包
     * 
     * @param customerId 用户钱包主键
     * @return 用户钱包
     */
    @Override
    public BizCustomerWallet selectBizCustomerWalletByCustomerId(Long customerId) {
        return bizCustomerWalletMapper.selectBizCustomerWalletByCustomerId(customerId);
    }
    @Override
    public BizCustomerWallet selectBizCustomerWalletByCustomerAccount(String account) {
        BizCustomer customer = bizCustomerMapper.selectBizCustomerByOpenId(account);
        if(null == customer){
            log.error("卡号【{}】不存在,返回默认钱包",account);
            return initBizCustomerWallet();
        }
        return customerWallet(customer.getId());
    }
    /**
     * 查询用户钱包
     *
     * @param customerId 用户钱包主键
     * @return 用户钱包
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public BizCustomerWallet customerWallet(Long customerId) {
        BizCustomerWallet wallet = bizCustomerWalletMapper.selectBizCustomerWalletByCustomerId(customerId);
        if(null != wallet){
            return wallet;
        }
        wallet = initBizCustomerWallet();
        wallet.setCreateBy(SecurityUtils.getStrUserId());
        wallet.setCustomerId(customerId);
        insertBizCustomerWallet(wallet);
        return wallet;
    }
    /**
     * 查询用户钱包列表
     * 
     * @param bizCustomerWallet 用户钱包
     * @return 用户钱包
     */
    @Override
    public List<BizCustomerWallet> selectBizCustomerWalletList(BizCustomerWallet bizCustomerWallet) {
        return bizCustomerWalletMapper.selectBizCustomerWalletList(bizCustomerWallet);
    }

    /**
     * 新增用户钱包
     * 
     * @param bizCustomerWallet 用户钱包
     * @return 结果
     */
    @Override
    public int insertBizCustomerWallet(BizCustomerWallet bizCustomerWallet) {
        bizCustomerWallet.setCreateTime(DateUtils.getNowDate());
        return bizCustomerWalletMapper.insertBizCustomerWallet(bizCustomerWallet);
    }

    /**
     * 初始化钱包
     * @return BizCustomerWallet
     */
    private BizCustomerWallet initBizCustomerWallet(){
        BizCustomerWallet wallet = new BizCustomerWallet();
        wallet.setBalance(BigDecimal.ZERO);
        wallet.setBalanceTranNo("");
        wallet.setDeposit(BigDecimal.ZERO);
        wallet.setDepositTranNo("");
        wallet.setStatus(EnableStatus.ENABLE.getCode());
        wallet.setRemark("用户初始化钱包,当前余额为0元");
        return wallet;
    }
    /**
     * 充值
     *
     * @param bizCustomerTranLog 用户钱包
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public  synchronized int rechargeSave(String opMsg,BizCustomerTranLog bizCustomerTranLog){
        BizCustomerWallet wallet = selectBizCustomerWalletByCustomerId(bizCustomerTranLog.getCustomerId());
        if(null == wallet){
            wallet = initBizCustomerWallet();
            wallet.setCustomerId(bizCustomerTranLog.getCustomerId());
            wallet.setCreateBy(bizCustomerTranLog.getCreateBy());
            wallet.setRemark("平台为用户创建钱包,当前余额为0元");
            insertBizCustomerWallet(wallet);
        }
        if(StringUtils.isBlank(bizCustomerTranLog.getTranNo())){
            bizCustomerTranLog.setTranNo(OrderNoUtils.getOrderNo());
        }
        bizCustomerTranLog.setTranFee(bizCustomerTranLog.getPayFee());
        bizCustomerTranLog.setStatus(EnableStatus.ENABLE.getCode());
        bizCustomerTranLog.setCreateTime(DateUtils.getNowDate());
        StringBuilder rk = new StringBuilder();
        if(StringUtils.isNotBlank(bizCustomerTranLog.getRemark())){
            rk.append("《").append(bizCustomerTranLog.getRemark()).append("》");
        }
        StringBuilder wrk = new StringBuilder(rk);
        String opType = BillChangeType.getDesc(bizCustomerTranLog.getBillChangeType());
        if(BillChangeType.IN.getCode().equals(bizCustomerTranLog.getBillChangeType())){
            wallet.setBalance(BigDecimalUtil.add(bizCustomerTranLog.getPayFee(),wallet.getBalance()));
        }else if(BillChangeType.OUT.getCode().equals(bizCustomerTranLog.getBillChangeType())){
            BigDecimal at = BigDecimalUtil.sub(wallet.getBalance(),bizCustomerTranLog.getPayFee());
            if(at.doubleValue() < 0){
                throw new BaseException("余额不足");
            }
            wallet.setBalance(at);
        }else {
            throw new BaseException("未授权操作类型");
        }
        wrk.append(opMsg).append("【本次").append(opType).append(bizCustomerTranLog.getPayFee()).append("元,当前余额:").append(wallet.getBalance()).append(",操作时间:").append(DateUtils.now()).append("】");
        wallet.setRemark(wrk.toString());
        wallet.setBalanceTranNo(bizCustomerTranLog.getTranNo());
        wallet.setUpdateTime(DateUtils.getNowDate());
        wallet.setUpdateBy(bizCustomerTranLog.getCreateBy());
        updateBizCustomerWallet(wallet);
        bizCustomerTranLog.setRemark(wallet.getRemark());
        return bizCustomerTranLogMapper.insertBizCustomerTranLog(bizCustomerTranLog);
    }
    /**
     * 修改用户钱包
     * 
     * @param bizCustomerWallet 用户钱包
     * @return 结果
     */
    @Override
    public int updateBizCustomerWallet(BizCustomerWallet bizCustomerWallet) {
        bizCustomerWallet.setUpdateTime(DateUtils.getNowDate());
        return bizCustomerWalletMapper.updateBizCustomerWallet(bizCustomerWallet);
    }

    /**
     * 批量删除用户钱包
     * 
     * @param customerIds 需要删除的用户钱包主键
     * @return 结果
     */
    @Override
    public int deleteBizCustomerWalletByCustomerIds(String customerIds) {
        return bizCustomerWalletMapper.deleteBizCustomerWalletByCustomerIds(Convert.toStrArray(customerIds));
    }

    /**
     * 删除用户钱包信息
     * 
     * @param customerId 用户钱包主键
     * @return 结果
     */
    @Override
    public int deleteBizCustomerWalletByCustomerId(Long customerId) {
        return bizCustomerWalletMapper.deleteBizCustomerWalletByCustomerId(customerId);
    }
}
